package com.colin.action;

import com.colin.git.MrRequestService;
import com.colin.git.entity.MrCreateDTO;
import com.colin.ui.component.MergeDialogView;
import com.colin.ui.component.TableRendererUtils;
import com.colin.util.NotificationUtil;
import com.colin.util.PropertiesManager;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.wm.ToolWindow;
import com.intellij.openapi.wm.ToolWindowFactory;
import com.intellij.openapi.wm.WindowManager;
import com.intellij.ui.content.Content;
import com.intellij.ui.content.ContentFactory;
import com.intellij.ui.content.ContentManager;
import org.apache.commons.lang3.StringUtils;
import org.jetbrains.annotations.NotNull;

import javax.swing.*;
import javax.swing.event.DocumentEvent;
import javax.swing.event.DocumentListener;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableModel;
import javax.swing.table.TableRowSorter;
import java.awt.*;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;

import static com.colin.ColinConstant.GIT_PRIVATE_TOKEN;

public class GitMergeRequestFactory
        implements ToolWindowFactory {

    private final static String[] columnNames = {"合并名称", "提交时间", "状态", "提交人", "合并来源", "目标分支", "合并人", "更新时间", "操作"};
    private final JPanel jPanel = new JPanel(new BorderLayout());

    private JTextField textField = new JTextField(30);

    private Object[][] tableData = {};
    // 创建一个表格模型
    private DefaultTableModel model = new DefaultTableModel(tableData, columnNames);

    private JTable table = new JTable(model);

    private Project project;

    @Override
    public void createToolWindowContent(@NotNull Project project, @NotNull ToolWindow toolWindow) {
        this.project = project;
        // 获取内容工厂的实例
        ContentFactory contentFactory = ContentFactory.getInstance();
        // 获取 ToolWindow 显示的内容
        Content content = contentFactory.createContent(
                this.instanceView(),
                "Merge Info", false);
        // 设置 ToolWindow 显示的内容
        ContentManager contentManager = toolWindow.getContentManager();
        contentManager.addContent(content);
        textField.addActionListener(e -> {
            PropertiesManager.save(GIT_PRIVATE_TOKEN, textField.getText());
            refreshTable();
        });
    }


    public JComponent instanceView() {
        JLabel label = new JLabel("""
                <HTML>
                    <h2>PRIVATE_TOKEN</h2>
                </HTML>
                """);
        JPanel header = new JPanel(new BorderLayout());
        header.add(label, BorderLayout.WEST);
        textField.setText(PropertiesManager.getString(GIT_PRIVATE_TOKEN));
        header.add(textField, BorderLayout.CENTER);

        JPanel buttonPanel = new JPanel(new BorderLayout());
        Label refresh = new Label("刷新");
        refresh.addMouseListener(new MouseListener() {
            @Override
            public void mouseClicked(MouseEvent e) {
                refreshTable();
            }

            @Override
            public void mousePressed(MouseEvent e) {
            }

            @Override
            public void mouseReleased(MouseEvent e) {
            }

            @Override
            public void mouseEntered(MouseEvent e) {
            }

            @Override
            public void mouseExited(MouseEvent e) {
            }
        });
        buttonPanel.add(refresh, BorderLayout.WEST);
        Button createButton = new Button("创建");
        createButton.addMouseListener(new MouseListener() {
            @Override
            public void mouseClicked(MouseEvent e) {
                MergeDialogView dialog = new MergeDialogView(WindowManager.getInstance().getFrame(project), text -> {
                    // 在这里处理提交按钮的点击事件
                    String title = text.get(0);
                    MrCreateDTO mrCreateDTO = new MrCreateDTO();
                    mrCreateDTO.setId("35");
                    mrCreateDTO.setTitle(title);
                    mrCreateDTO.setSourceBranch(text.get(1));
                    mrCreateDTO.setTargetBranch(text.get(2));
                    if (StringUtils.isBlank(textField.getText())) {
                        NotificationUtil.error("请填写private_token");
                        return;
                    }
                    NotificationUtil.info("创建MR: " + MrRequestService.createMr(mrCreateDTO, textField.getText()));
                });
                // 设置对话框的大小、位置、可见性等
                dialog.pack();
                dialog.setLocationRelativeTo(WindowManager.getInstance().getFrame(project));
                dialog.setVisible(true);
            }

            @Override
            public void mousePressed(MouseEvent e) {

            }

            @Override
            public void mouseReleased(MouseEvent e) {

            }

            @Override
            public void mouseEntered(MouseEvent e) {

            }

            @Override
            public void mouseExited(MouseEvent e) {

            }
        });
        buttonPanel.add(createButton, BorderLayout.EAST);
        header.add(label, BorderLayout.WEST);
        header.add(buttonPanel, BorderLayout.EAST);

        jPanel.add(header, BorderLayout.NORTH);
        buildTable(jPanel);
        jPanel.setVisible(true);
        return jPanel;
    }

    private void buildTable(JPanel jPanel) {
        JPanel thisPanel = new JPanel(new BorderLayout());
        if (StringUtils.isBlank(textField.getText())) {
            NotificationUtil.error("请填写private_token");
        } else {
            // 定义数据
            tableData = MrRequestService.queryMrInfo(textField.getText());
        }
        // 创建一个行排序器并设置到表格上
        TableRowSorter<TableModel> sorter = new TableRowSorter<>(table.getModel());
        table.setRowSorter(sorter);

        // 创建一个文本框用于过滤，并添加一个监听器来更新过滤器
        JTextField filterText = new JTextField();
        filterText.getDocument().addDocumentListener(new DocumentListener() {
            public void changedUpdate(DocumentEvent e) {
                newFilter();
            }

            public void insertUpdate(DocumentEvent e) {
                newFilter();
            }

            public void removeUpdate(DocumentEvent e) {
                newFilter();
            }

            private void newFilter() {
                String text = filterText.getText();
                if (text.trim().isEmpty()) {
                    sorter.setRowFilter(null);
                } else {
                    sorter.setRowFilter(RowFilter.regexFilter("(?i)" + text));
                }
            }
        });

        model.setDataVector(tableData, columnNames);
        table.getColumn("操作").setCellRenderer(new TableRendererUtils.ButtonRenderer());
        table.getColumn("操作").setCellEditor(new TableRendererUtils.ButtonEditor(new JCheckBox()));
        table.repaint();
        thisPanel.add(new JScrollPane(table), BorderLayout.CENTER);
        thisPanel.add(filterText, BorderLayout.NORTH);
        jPanel.add(thisPanel, BorderLayout.CENTER);
    }


    public void refreshTable() {
        if (StringUtils.isBlank(textField.getText())) {
            NotificationUtil.error("请填写private_token");
            return;
        }
        tableData = MrRequestService.queryMrInfo(textField.getText());
        model.setDataVector(tableData, columnNames);
        // 设置按钮渲染器和编辑器
        table.getColumn("操作").setCellRenderer(new TableRendererUtils.ButtonRenderer());
        table.getColumn("操作").setCellEditor(new TableRendererUtils.ButtonEditor(new JCheckBox()));
        table.repaint();
        jPanel.repaint();
    }
}
